const mysql = require('mysql2/promise');

// 数据库配置
const dbConfig = {
  host: '43.143.253.188',
  port: 3306,
  user: 'nextjs',
  password: 'yEAiRE2jcxTyRBy5',
  database: 'nextjs'
};

async function checkAndCreateUserTables() {
  let connection;
  
  try {
    console.log('🔍 检查数据库连接...');
    connection = await mysql.createConnection(dbConfig);
    console.log('✅ 数据库连接成功');
    
    // 检查 users 表是否存在
    console.log('\n📋 检查 users 表...');
    const [tables] = await connection.execute("SHOW TABLES LIKE 'users'");
    
    if (tables.length === 0) {
      console.log('❌ users 表不存在，开始创建...');
      
      const createUsersTableSQL = `
        CREATE TABLE \`users\` (
          \`id\` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户ID',
          \`mobile\` varchar(32) NOT NULL COMMENT '手机号',
          \`passwordHash\` varchar(64) NOT NULL COMMENT '密码哈希',
          \`accessToken\` varchar(128) DEFAULT NULL COMMENT '访问令牌',
          \`tokenIssuedAt\` bigint(20) DEFAULT NULL COMMENT '令牌签发时间',
          \`channel\` varchar(64) DEFAULT NULL COMMENT '渠道',
          \`inviteCode\` varchar(64) DEFAULT NULL COMMENT '邀请码',
          \`createdAt\` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
          \`updatedAt\` datetime DEFAULT NULL COMMENT '更新时间',
          PRIMARY KEY (\`id\`),
          UNIQUE KEY \`uk_mobile\` (\`mobile\`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户表'
      `;
      
      await connection.execute(createUsersTableSQL);
      console.log('✅ users 表创建成功');
      
      // 插入测试用户
      console.log('\n👤 插入测试用户...');
      const insertTestUserSQL = `
        INSERT INTO users (mobile, passwordHash, channel, inviteCode, createdAt) 
        VALUES (?, ?, ?, ?, NOW())
      `;
      
      const testUser = {
        mobile: '13800138000',
        passwordHash: '123456', // 简单密码用于测试
        channel: 'test',
        inviteCode: 'TEST001'
      };
      
      await connection.execute(insertTestUserSQL, [
        testUser.mobile,
        testUser.passwordHash,
        testUser.channel,
        testUser.inviteCode
      ]);
      
      console.log('✅ 测试用户插入成功');
      console.log(`   手机号: ${testUser.mobile}`);
      console.log(`   密码: ${testUser.passwordHash}`);
      
    } else {
      console.log('✅ users 表已存在');
      
      // 检查是否有用户数据
      const [users] = await connection.execute("SELECT COUNT(*) as count FROM users");
      console.log(`   当前用户数量: ${users[0].count}`);
      
      if (users[0].count === 0) {
        console.log('\n👤 插入测试用户...');
        const insertTestUserSQL = `
          INSERT INTO users (mobile, passwordHash, channel, inviteCode, createdAt) 
          VALUES (?, ?, ?, ?, NOW())
        `;
        
        const testUser = {
          mobile: '13800138000',
          passwordHash: '123456',
          channel: 'test',
          inviteCode: 'TEST001'
        };
        
        await connection.execute(insertTestUserSQL, [
          testUser.mobile,
          testUser.passwordHash,
          testUser.channel,
          testUser.inviteCode
        ]);
        
        console.log('✅ 测试用户插入成功');
      }
    }
    
    // 检查其他相关表
    console.log('\n📋 检查其他相关表...');
    const tableNames = ['areas', 'characters', 'casino_rounds'];
    
    for (const tableName of tableNames) {
      const [tableExists] = await connection.execute(`SHOW TABLES LIKE '${tableName}'`);
      if (tableExists.length > 0) {
        console.log(`   ✅ ${tableName} 表存在`);
      } else {
        console.log(`   ❌ ${tableName} 表不存在`);
      }
    }
    
    console.log('\n🎉 数据库检查完成！');
    
  } catch (error) {
    console.error('❌ 数据库操作失败:', error.message);
  } finally {
    if (connection) {
      await connection.end();
      console.log('\n🔌 数据库连接已关闭');
    }
  }
}

// 运行检查
checkAndCreateUserTables(); 